import React, { useMemo, Children, Fragment, cloneElement } from 'react';
import { View, Text, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import theme from '@/theme';

import './index.scss';

const AvatarGroup = ({
  size = theme.avatar.size,
  radiusType = theme.avatar.radiusType,
  color,
  bgColor,
  iconSize,
  children,
  span = -16,
  max,
  maxProps,
}) => {
  const itemSize = theme.avatar.sizes[size];

  return (
    <View className={classNames('pd-avatarGroup', 'pd-avatarGroup--' + size)}>
      {Children.map(children, (child, index) => {
        if ((max ?? false) !== false) {
          if (index > max) {
            return <Fragment />;
          } else if (index === max) {
            return (
              <Avatar
                size={size}
                radiusType={radiusType}
                color={color}
                bgColor={bgColor}
                iconSize={iconSize}
                {...maxProps}
                className='pd-avatarGroup__avatar'
                style={{
                  left: Taro.pxTransform(index * (itemSize + span)),
                }}>
                {maxProps?.children || '+N'}
              </Avatar>
            );
          }
        }
        return cloneElement(child, {
          size,
          radiusType,
          color,
          bgColor,
          iconSize,
          className: classNames(child.props.className, 'pd-avatarGroup__avatar'),
          style: {
            left: Taro.pxTransform(index * (itemSize + span)),
          },
        });
      })}
    </View>
  );
};

export const Avatar = ({
  size = theme.avatar.size,
  radiusType = theme.avatar.radiusType,
  color,
  bgColor,
  url = theme.avatar.url,
  icon,
  iconSize,
  className,
  style,
  children,
  ...props
}) => {
  const [viewStyle, textStyle] = useMemo(() => {
    const _sty = { ...style };
    if (bgColor) {
      _sty.backgroundColor = bgColor;
    }
    const __style = {};
    if (color) {
      __style.color = color;
    }
    return [_sty, __style];
  }, [color, bgColor, style]);

  return (
    <View className={classNames('pd-avatar', 'pd-avatar--' + size, 'pd-avatar--' + radiusType, className)} style={viewStyle} {...props}>
      {url ? (
        <Image src={url} className='pd-avatar__image' mode='aspectFill' />
      ) : icon ? (
        React.cloneElement(icon, { size: iconSize || theme.avatar.iconSize, color: color || theme.avatar.color })
      ) : (
        <Text className={classNames('pd-avatar__text pd-avatar--text-color', 'pd-avatar__text--' + size)} style={textStyle}>
          {children || 'User'}
        </Text>
      )}
    </View>
  );
};

Avatar.Group = AvatarGroup;
export default Avatar;
